package top.linuyx.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.linuyx.realm.AccountRealm;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Linuyx
 * @Description Shiro配置类
 * @Date Created in 2021-04-08 21:39
 */

@Configuration
public class ShiroConfig {

    /**
     * 创建ShiroFilter(拦截所有请求)
     *
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //给ShiroFilter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        Map<String, String> map = new HashMap<>();
        map.put("/**", "anon");
        map.put("/login/**", "anon");//登录请求放行
        map.put("/register", "anon");//注册请求放行

        //将map集合set给ShiroFilter
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        //未认证返回的url
        shiroFilterFactoryBean.setLoginUrl("/please-login");

        return shiroFilterFactoryBean;
    }

    /**
     * 创建安全管理器
     *
     * @param realm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //给安全管理器设置realm
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    @Bean
    public Realm getRealm() {
        AccountRealm accountRealm = new AccountRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法为MD5
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //这是散列次数
        hashedCredentialsMatcher.setHashIterations(1024);

        accountRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return accountRealm;
    }
}
